<?php
namespace App\Services\Impl;
use App\Library\FileLibraryInterFace;
use App\Services\FileServiceInterFace;
use Log;
use Illuminate\Support\Facades\Auth;
use App\Pojo\ResponsePojo;
use App\Constant\HttpStatus;
use App\Library\UserLibraryInterface;
use Illuminate\Support\Facades\Redis;
final class FileServiceImpl implements FileServiceInterFace{


    private $fileLibrary;

    public function __construct(FileLibraryInterFace $fileLibraryInterFace){
        $this->fileLibrary = $fileLibraryInterFace;
    }

    /**
     * 将B转换为MB
     * @param int $kb 千字节大小
     * @return float 返回MB大小，保留2位小数
     */
    private function kbToMb($kb) {
        return round($kb / 1024 / 1024, 2);
    }


    public function getImageList($credentials){
        // 如果Redis中没有数据，从数据库获取
        $paginator = $this->fileLibrary->getImageList($credentials['currentPage'], $credentials['pageSize']);
        
        $uploadedFiles = [];
        foreach ($paginator->items() as $image) {    
            $uploadedFiles[] = [
                'fileName' => $image['file_name'],
                'fileSize' => $this->kbToMb($image['file_size']),
                'fileType' => $image['file_type'],
                'mime_type' => $image['mime_type'],
                'id' => $image['id'],
                'file_hash' => $image['file_hash'],
                'createdAt' => $image['created_at'],
                'storage_type' => $image['storage_type'],
                'url' => asset('storage/' . $image['file_path']),
            ];
        }
        
        $imageList = [
            'list' => $uploadedFiles,
            'total' => $paginator->total(),
            'per_page' => $paginator->perPage(),
            'current_page' => $paginator->currentPage(),
            'last_page' => $paginator->lastPage()
        ];

        // 将数据存入Redis，设置过期时间为1小时
        return ResponsePojo::success(HttpStatus::OK, HttpStatus::getStatusMessage(HttpStatus::OK), $imageList);
    }

    public function deleteImageMager($credentials){
        $this->fileLibrary->deleteImageMager($credentials);
        return ResponsePojo::success(HttpStatus::OK, HttpStatus::getStatusMessage(HttpStatus::OK), null);
    }


    public function getImageListByHashs($fileHashs){
        $fileLibrary = $this->fileLibrary->getImageListByHashs($fileHashs);
        return $fileLibrary;
    }


    public function getImageListByuserId($logId){
        $fileLibrary = $this->fileLibrary->getImageListByuserId($logId);
        return $fileLibrary;
    }

    
}